<template>
    <a-modal
        title="编码类型"
        :visible="visible"
        width="1200px"
        :footer="null"
        @cancel="handleCancel"
    >
        <div class="code-type-modal-content">
            <!-- 顶部控制栏 -->
            <div class="control-bar">
                <a-row :gutter="16" align="middle">
                    <a-col :span="8">
                        <div style="display: flex; align-items: center;">
                            <span style="margin-right: 8px; white-space: nowrap;">编码类型:</span>
                            <a-select v-model="selectedCodeType" style="flex: 1;" @change="handleCodeTypeChange">
                                <a-select-option 
                                    v-for="option in codeTypeOptions" 
                                    :key="option" 
                                    :value="option"
                                >
                                    {{ option || option }}
                                </a-select-option>
                            </a-select>
                        </div>
                    </a-col>
                    <!-- 添加编辑框和一个按钮，用来搜索编码或者中文名称 -->
                    <a-col :span="8">
                        <a-input-search
                            v-model="searchKeyword"
                            placeholder="搜索编码或中文名称"
                            style="width: 200px; margin-right: 8px;"
                            allow-clear
                            @search="handleSearch"
                            @change="handleInputChange"
                        />
                    </a-col>

                    <a-col :span="8" style="text-align: right;">
                        <a-button type="primary" @click="fillSelectedFactors">
                            将选中因子填充到变量名称
                        </a-button>
                    </a-col>
                </a-row>
            </div>

            <!-- 编码类型表格 -->
            <div class="table-wrapper">
                <a-table
                    :columns="codeTypeColumns"
                    :data-source="currentPageData"
                    :row-selection="{ 
                        selectedRowKeys: selectedRowKeys, 
                        onChange: onSelectionChange,
                        type: 'radio'
                    }"
                    row-key="code"
                    size="middle"
                    :pagination="false"
                >
                    <template slot="sequence" slot-scope="text, record, index">
                        {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
                    </template>
                </a-table>
            </div>

            <!-- 固定的分页器 -->
            <div class="pagination-wrapper">
                <a-pagination
                    v-model="pagination.current"
                    :total="filteredCodeTypeData.length"
                    :page-size="pagination.pageSize"
                    :show-size-changer="true"
                    :show-quick-jumper="true"
                    :page-size-options="['10', '20', '30', '50']"
                    show-total
                    @change="handlePageChange"
                    @showSizeChange="handlePageSizeChange"
                >
                    <template slot="buildOptionText" slot-scope="props">
                        {{ props.value }}条/页
                    </template>
                </a-pagination>
            </div>
        </div>
    </a-modal>
</template>

<script>
import tabManager from '@/api/tab-manager'

export default {
    name: 'CodeTypeModal',
    props: {
        visible: { type: Boolean, required: true }
    },
    data() {
        return {
            selectedCodeType: 'surface_water',
            selectedRowKeys: [],
            selectedRows: [],
            codeTypeData: [],
            codeTypeOptions: [], // 编码类型选项列表
            searchKeyword: '', // 搜索关键词
            filteredCodeTypeData: [], // 过滤后的数据
            pagination: {
                current: 1,
                pageSize: 10
            },
            codeTypeColumns: [
                {
                    title: '序号',
                    dataIndex: 'sequence',
                    key: 'sequence',
                    width: 60,
                    scopedSlots: { customRender: 'sequence' }
                },
                {
                    title: '编码',
                    dataIndex: 'code',
                    key: 'code',
                    width: 120
                },
                {
                    title: '中文名称',
                    dataIndex: 'chineseName',
                    key: 'chineseName',
                    width: 200
                },
                {
                    title: '原编码',
                    dataIndex: 'originalCode',
                    key: 'originalCode',
                    width: 120
                },
                {
                    title: '缺省计量单位(浓度)',
                    dataIndex: 'concentrationUnit',
                    key: 'concentrationUnit',
                    width: 150
                },
                {
                    title: '缺省计量单位(排放量)',
                    dataIndex: 'emissionUnit',
                    key: 'emissionUnit',
                    width: 150
                },
                {
                    title: '缺省数据类型(浓度)',
                    dataIndex: 'concentrationDataType',
                    key: 'concentrationDataType',
                    width: 150
                }
            ]
        }
    },
    computed: {
        // 计算当前页要显示的数据
        currentPageData() {
            const start = (this.pagination.current - 1) * this.pagination.pageSize
            const end = start + this.pagination.pageSize
            return this.filteredCodeTypeData.slice(start, end)
        }
    },
    watch: {
        selectedCodeType: {
            handler(newType) {
                this.loadCodeTypeData(newType)
            },
            immediate: false
        },
        visible: {
            handler(val) {
                if (val) {
                    // 只在对话框打开时加载编码类型选项
                    this.loadCodeTypeOptions()
                }
            },
            immediate: false
        }
    },
    methods: {
        handleCancel() {
            this.$emit('cancel')
        },
        
        handleCodeTypeChange(value) {
            console.log('🔄 [CodeTypeModal] 编码类型变化:', value)
            this.selectedCodeType = value
        },
        
        onSelectionChange(selectedRowKeys, selectedRows) {
            console.log('🔄 [CodeTypeModal] 选择变化:', { selectedRowKeys, selectedRows })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        
        fillSelectedFactors() {
            console.log('🔄 [CodeTypeModal] 填充选中因子')
            if (this.selectedRows.length === 0) {
                this.$message.warning('请先选择要填充的因子')
                return
            }
            
            // 将选中的行数据传递给父组件
            this.$emit('factors-selected', this.selectedRows)
            this.handleCancel()
        },

        // 加载编码类型选项列表
        async loadCodeTypeOptions() {
            console.log('🔍 [CodeTypeModal] 开始加载编码类型选项列表')
            try {
                const response = await tabManager.monitor.getCodeTypeList()
                if (response && response.code === 0) {
                    this.codeTypeOptions = JSON.parse(response.data) || []
                    console.log('✅ [CodeTypeModal] 编码类型选项加载完成:', this.codeTypeOptions)
                    
                    // 如果有选项，设置第一个为默认值
                    if (this.codeTypeOptions.length > 0) {
                        this.selectedCodeType = this.codeTypeOptions[0]
                    }
                } else {
                    console.warn('⚠️ [CodeTypeModal] 编码类型选项加载失败，使用默认选项')
                    // 使用默认选项
                    this.codeTypeOptions = [
                        { value: 'surface_water', label: '地表水质量监测' },
                        { value: 'groundwater', label: '地下水质量监测' },
                        { value: 'air_quality', label: '空气质量监测' }
                    ]
                }
            } catch (error) {
                console.error('❌ [CodeTypeModal] 加载编码类型选项失败:', error)
                this.$message.error('加载编码类型选项失败')
                // 使用默认选项
                this.codeTypeOptions = [
                    { value: 'surface_water', label: '地表水质量监测' },
                    { value: 'groundwater', label: '地下水质量监测' },
                    { value: 'air_quality', label: '空气质量监测' }
                ]
            }
        },
        
        // 加载编码类型数据
        async loadCodeTypeData(codeType) {
            console.log('🔍 [CodeTypeModal] 加载编码类型数据:', codeType)
            
            try {
                const response = await tabManager.monitor.getCodeTypeData(codeType)
                if (response && response.code === 0) {
                    this.codeTypeData = JSON.parse(response.data) || []
                    this.selectedRows = [] // 需要清空
                    console.log('✅ [CodeTypeModal] 编码类型数据加载完成:', this.codeTypeData)
                    // 更新过滤后的数据
                    this.updateFilteredData()
                } else {
                    console.warn('⚠️ [CodeTypeModal] 编码类型数据加载失败，使用默认数据')
                    // 使用默认数据
                    this.loadDefaultCodeTypeData(codeType)
                }
            } catch (error) {
                console.error('❌ [CodeTypeModal] 加载编码类型数据失败:', error)
                this.$message.error('加载编码类型数据失败')
                // 使用默认数据
                this.loadDefaultCodeTypeData(codeType)
            }
        },

        // 加载默认的编码类型数据（当接口不可用时使用）
        loadDefaultCodeTypeData(codeType) {
            console.log('🔄 [CodeTypeModal] 加载默认编码类型数据:', codeType)
            
            switch (codeType) {
                case 'surface_water':
                    this.codeTypeData = [
                        {
                            code: 'w00000',
                            chineseName: '污水',
                            originalCode: 'B01',
                            concentrationUnit: '升/秒',
                            emissionUnit: '立方米',
                            concentrationDataType: 'N5.2'
                        },
                        {
                            code: 'w01001',
                            chineseName: 'pH值',
                            originalCode: '1',
                            concentrationUnit: '无量纲',
                            emissionUnit: '',
                            concentrationDataType: 'N2.2'
                        },
                        {
                            code: 'w01002',
                            chineseName: '色度',
                            originalCode: '2',
                            concentrationUnit: '[色]度',
                            emissionUnit: '',
                            concentrationDataType: 'N3.2'
                        },
                        {
                            code: 'w01003',
                            chineseName: '溶解性总固体',
                            originalCode: '3',
                            concentrationUnit: '毫克/升',
                            emissionUnit: '千克',
                            concentrationDataType: 'N4'
                        },
                        {
                            code: 'w01004',
                            chineseName: '悬浮物',
                            originalCode: '4',
                            concentrationUnit: '毫克/升',
                            emissionUnit: '千克',
                            concentrationDataType: 'N4'
                        },
                        {
                            code: 'w01005',
                            chineseName: '化学需氧量',
                            originalCode: '5',
                            concentrationUnit: '毫克/升',
                            emissionUnit: '千克',
                            concentrationDataType: 'N4'
                        }
                    ]
                    break
                case 'groundwater':
                    this.codeTypeData = [
                        {
                            code: 'g00000',
                            chineseName: '地下水',
                            originalCode: 'G01',
                            concentrationUnit: '升/秒',
                            emissionUnit: '立方米',
                            concentrationDataType: 'N5.2'
                        },
                        {
                            code: 'g01001',
                            chineseName: 'pH值',
                            originalCode: '1',
                            concentrationUnit: '无量纲',
                            emissionUnit: '',
                            concentrationDataType: 'N2.2'
                        }
                    ]
                    break
                case 'air_quality':
                    this.codeTypeData = [
                        {
                            code: 'a00000',
                            chineseName: '空气质量',
                            originalCode: 'A01',
                            concentrationUnit: '毫克/立方米',
                            emissionUnit: '千克',
                            concentrationDataType: 'N4'
                        },
                        {
                            code: 'a01001',
                            chineseName: '二氧化硫',
                            originalCode: '1',
                            concentrationUnit: '毫克/立方米',
                            emissionUnit: '千克',
                            concentrationDataType: 'N4'
                        }
                    ]
                    break
                default:
                    this.codeTypeData = []
            }
            
            console.log('✅ [CodeTypeModal] 默认编码类型数据加载完成:', this.codeTypeData.length)
            // 更新过滤后的数据
            this.updateFilteredData()
        },

        // 处理搜索
        handleSearch(value) {
            console.log('🔍 [CodeTypeModal] 搜索关键词:', value)
            // 确保 value 是字符串类型
            this.searchKeyword = typeof value === 'string' ? value : ''
            this.updateFilteredData()
        },

        // 处理输入变化
        handleInputChange(e) {
            const value = e.target.value
            console.log('🔍 [CodeTypeModal] 输入变化:', value)
            this.searchKeyword = value
            this.updateFilteredData()
        },

        // 清除搜索
        clearSearch() {
            console.log('🔄 [CodeTypeModal] 清除搜索')
            this.searchKeyword = ''
            this.updateFilteredData()
        },

        // 更新过滤后的数据
        updateFilteredData() {
            if (!this.searchKeyword) {
                // 如果没有搜索关键词，显示所有数据
                this.filteredCodeTypeData = [...this.codeTypeData]
            } else {
                // 根据搜索关键词过滤数据
                this.filteredCodeTypeData = this.codeTypeData.filter(item => {
                    const keyword = this.searchKeyword.toLowerCase()
                    return (
                        item.code.toLowerCase().includes(keyword) ||
                        item.chineseName.toLowerCase().includes(keyword) ||
                        (item.originalCode && item.originalCode.toLowerCase().includes(keyword))
                    )
                })
            }
            
            // 重置到第一页
            this.pagination.current = 1
            
            console.log('✅ [CodeTypeModal] 过滤后数据更新完成:', {
                total: this.codeTypeData.length,
                filtered: this.filteredCodeTypeData.length,
                keyword: this.searchKeyword
            })
        },

        // 处理页码变化
        handlePageChange(page, pageSize) {
            console.log('📄 [CodeTypeModal] 页码变化:', { page, pageSize })
            this.pagination.current = page
            this.pagination.pageSize = pageSize
        },

        // 处理每页条数变化
        handlePageSizeChange(current, size) {
            console.log('📄 [CodeTypeModal] 每页条数变化:', { current, size })
            this.pagination.current = 1
            this.pagination.pageSize = size
        }
    }
}
</script>

<style scoped>
.code-type-modal-content {
    height: 600px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}
.control-bar {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 16px;
    flex-shrink: 0;
}
.control-bar .ant-form-item {
    margin-bottom: 0;
}
.table-wrapper {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    margin-bottom: 16px;
}
.pagination-wrapper {
    flex-shrink: 0;
    padding: 12px 0;
    border-top: 1px solid #f0f0f0;
    background-color: #fff;
    text-align: right;
}
</style> 